"""
@File: schedule.py
@Project: 约个球
@Author: zhangjian
@Time: 2022.8.23 23:23
@Description: None
"""
from functools import wraps
from flask import Blueprint, request
from flask_restful import Resource, Api
from libs.amap import geo_response, geo_distance
from libs.response import generate_response
from model import db
from model.schedule import ScheduleManager
from model.user import UserManager
from libs.handler import default_error_handler
from libs.auth import login, create_token, verify_token, api_auth

schedule_bp = Blueprint("scheduleapi", __name__, url_prefix="/v1")
api = Api(schedule_bp)
api.handle_error = default_error_handler  # 异常标准化处理


class Invitation(Resource):
    """约球帖"""

    def get(self, location_x=None, location_y=None, id=None):
        """查询"""
        location_x = request.args.get("location_x")
        location_y = request.args.get("location_y")
        Invitations = ScheduleManager.query.all()
        for i in Invitations:
            if not geo_distance(location_x, location_y, i.location_x, i.location_y):
                Invitations.remove(i)
        if Invitations:
            # 双循环推导式得到订阅者列表
            subscribers = [user.username for item in Invitations for user in item.users]
            datas = []
            for item in Invitations:
                tmp_dict = dict(item)
                tmp_dict["subscribers"] = subscribers
                datas.append(tmp_dict)
            return generate_response(status_code=10001, message="get info success", data=datas)
        else:
            return generate_response(status_code=10001, message="not info")

    def post(self):
        """新增"""
        user_id = request.json.get("user_id")
        if UserManager.query.get(user_id) is not None:
            ScheduleManager.create_invitation(
                user_id=user_id,
                address=request.json.get("address"),
                time=request.json.get("time"),
                introduction=request.json.get("introduction"),
                location_x=geo_response(request.json.get("address"))[0],
                location_y=geo_response(request.json.get("address"))[1]
            )
            return generate_response(message="add invitation success")
        else:
            return generate_response(status_code=10001, message="user_id doesn't exist")

    def put(self, id):
        """修改"""
        schedule = ScheduleManager.query.get(id)
        if schedule is not None:
            user_id = request.json.get("user_id")
            if UserManager.query.get(user_id) is not None:
                ScheduleManager.create_invitation(
                    user_id=user_id,
                    address=request.json.get("address"),
                    time=request.json.get("time"),
                    introduction=request.json.get("introduction"),
                    location_x=geo_response(request.json.get("address"))[0],
                    location_y=geo_response(request.json.get("address"))[1]
                )
                return generate_response(message="update invitation success")
            else:
                return generate_response(status_code=10001, message="user_id doesn't exist")
        else:
            return generate_response(status_code=10001, message="invitation doesn't exist")

    def delete(self, id):
        """删除"""
        result = ScheduleManager.query.get(id)
        if result is not None:
            db.session.delete(result)
            db.session.commit()
            return generate_response(message="delete monitor success")
        else:
            return generate_response(status_code=10001, message="monitor doesn't exist")


api.add_resource(Invitation, "/invitation")
api.add_resource(Invitation, "/invitation/<int:id>", endpoint="invitationviewapi")


class Subscribe(Resource):
    """预约"""

    def post(self):
        """新增"""
        user_id = request.json.get("user_id")
        schedule_id = request.json.get("schedule_id")
        user = UserManager(id=user_id)
        schedule = ScheduleManager(id=schedule_id)

api.add_resource(Subscribe, "/subscribe")


# 针对这一类资源（get、post、put），都需要使用装饰器
api.decorators = [login]

